"use strict";

const Service = require("egg").Service;

class BlogService extends Service {
  // 首页博客查询
  async index({ pageNum, pageSize }) {
    const { ctx } = this;
    const query = {
      attributes: { exclude: ["content"] },
      limit: pageSize,
      offset: (pageNum - 1) * pageSize,
      order: [["created_at", "DESC"]],
    };
    const blogList = await ctx.model.Blog.findAll(query);
    // 获取标签和分类
    for (let i = 0; i < blogList.length; i++) {
      // 对应标签
      const blogId = blogList[i].blogId;
      const categoryId = blogList[i].categoryId;
      const tags = await ctx.service.tag.getTags(blogId);
      blogList[i].setDataValue("tags", tags);
      // 对应分类
      const category = await ctx.service.category.getCategory(categoryId);
      blogList[i].setDataValue("category", category);
    }
    return blogList;
  }

  async update(blog, id) {
    return await this.ctx.model.Blog.update(blog, {
      where: { blogId: id },
    });
  }

  async destroy(blogId) {
    return await this.ctx.model.Blog.destroy({
      where: { blogId },
    });
  }

  // 查询所有博客 按分类分组
  async getBlogsGroupByCategory() {
    const ctx = this.ctx;
    const category = await ctx.model.Category.findAll();
    // 有分类的博客
    const blogList = [];
    for (let i = 0; i < category.length; i++) {
      const blogs = await ctx.model.Blog.findAll({
        attributes: ["blogId", "title", "createdAt"],
        where: {
          categoryId: category[i].categoryId,
        },
        order: [["createdAt", "desc"]],
      });
      blogList.push({
        category: category[i],
        blogs,
        total: blogs.length,
      });
    }
    // 没分类的博客
    const blogListNotCategory = await ctx.model.Blog.findAll({
      attributes: ["blogId", "title", "createdAt"],
      order: [["createdAt", "desc"]],
      where: { categoryId: null },
    });
    blogList.push({
      category: { categoryId: 0, title: "未分类" },
      blogs: blogListNotCategory,
      total: blogListNotCategory.length,
    });
    return blogList;
  }

  // 查询某个分类下的博客
  async getBlogsByCategoryId(categoryId) {
    const { ctx } = this;
    const blogList = await ctx.model.Blog.findAll({
      attributes: ["blogId", "title", "createdAt"],
      where: { categoryId },
      order: [["createdAt", "desc"]],
    });
    return blogList;
  }
}

module.exports = BlogService;
